<template>
  <div>
    <!-- 查询 -->
    <el-row>
      <el-col :span="24" class="addRole">
        <el-popover placement="bottom-start" width="1000" style="margin-right:10px;" trigger="click">
          <el-form :inline="true" :model="search">
              <el-form-item label="订单号" >
                <el-input v-model="search.orderNums"></el-input>
              </el-form-item>
              <el-form-item label="任务自编号" >
                <el-input v-model="search.taskCode"></el-input>
              </el-form-item>
              <el-form-item label="供应商" >
                <el-autocomplete  class="width220" v-model="search.supplierName" :fetch-suggestions="querySearchAsync" placeholder="请输入供应商名称" @select="handleSelect"></el-autocomplete>
              </el-form-item>
              <el-button type="primary" @click="searchBtn">确认</el-button>
          </el-form>
          <el-button slot="reference" type="primary" icon="el-icon-search">查询</el-button>
        </el-popover>
         <el-button  type="primary" @click="showDialog('insert')" v-if="status!=='1'&&(!postData.isPay&&!postData.isArrive)">新增</el-button>
      </el-col>
    </el-row>
    <!-- 任务列表 -->
    <purchaseTaskList ref="tableList29" :postData="postData">
      <template v-slot:default="scope">
        <el-button @click="showDialog('update',scope.row)" type="text" size="small">详情</el-button>
      </template>
    </purchaseTaskList>
    <!-- 采购任务详情 -->
    <el-dialog class="bodyNopaddingTop"  :title="dialog.title" width="800px" center :visible.sync="dialog.isShow" v-dialogDrag :close-on-click-modal='false'>
        <el-tabs v-model="dialog.activeName" @tab-click="handleClick" >
          <el-tab-pane label="任务信息" name="1">
            <el-form :inline="true" class="demo-form-inline" v-model="dialog.formData" label-position="right" label-width="130px">
              <h3 class="dialog-plate-title">任务基本信息</h3>
              <el-form-item label="订单号"  v-if="dialog.type!=='insert'" ><el-input v-model="dialog.formData.orderNums" disabled class="width220"></el-input></el-form-item>
              <el-form-item label="任务自编号"><el-input v-model="dialog.formData.taskCode" class="width220"></el-input></el-form-item>
              <el-form-item label="供应商">
                <el-autocomplete  class="width220" v-model="dialog.formData.supplierName.name" :fetch-suggestions="querySearchAsync" placeholder="请输入供应商名称" @select="handleSelect1"></el-autocomplete>
              </el-form-item>
              <el-form-item label="采购物品名称" v-if="dialog.type!=='insert'"><el-input v-model="dialog.formData.cgTaskDetail" class="width220" disabled ></el-input></el-form-item>
              <el-form-item label="采购人员">
                <el-select v-model="dialog.formData.cgPerson" placeholder="请选择" class="width220">
                  <el-option
                    v-for="item in allCgPersonList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="创建人" v-if="dialog.type!=='insert'"><el-input v-model="dialog.formData.creatorName" disabled class="width220"></el-input></el-form-item>
              <el-form-item label="创建时间" v-if="dialog.type!=='insert'"><el-input v-model="dialog.formData.createTime" disabled class="width220"></el-input></el-form-item>
              <div v-if="dialog.type!=='insert'">
              <h3 class="dialog-plate-title">启动信息</h3>
              <el-form-item label="启动" >
                <el-select v-model="dialog.formData.isStart"  placeholder="请选择是否启动" class="width220">
                  <el-option label="否" :value="0"></el-option>
                  <el-option label="是" :value="1"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="启动时间" >
                <el-date-picker class="width220 noMargin" v-model="dialog.formData.startTime" type="datetime" placeholder="选择启动时间" disabled></el-date-picker>
              </el-form-item>
              <h3 class="dialog-plate-title">发货信息</h3>
              <el-form-item label="是否开始备货" >
                <el-select v-model="dialog.formData.isStockUp"  placeholder="请选择是否开始备货" class="width220">
                  <el-option label="否" :value="0"></el-option>
                  <el-option label="是" :value="1"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="备货时间" >
                <el-date-picker class="width220 noMargin" v-model="dialog.formData.stockUpTime" type="datetime" placeholder="开始备货时间"></el-date-picker>
              </el-form-item>
              <el-form-item label="备货过程是否检查" >
                <el-select v-model="dialog.formData.isCheckUp"  placeholder="请选择备货过程是否检查" class="width220">
                  <el-option label="否" :value="0"></el-option>
                  <el-option label="是" :value="1"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="检查时间" >
                <el-date-picker class="width220 noMargin" v-model="dialog.formData.checkUpTime" type="datetime" placeholder="检查时间"></el-date-picker>
              </el-form-item>
              <el-form-item label="是否已发货" >
                <el-select v-model="dialog.formData.isDeliver"  placeholder="请选择是否已发货" class="width220">
                  <el-option label="否" :value="0"></el-option>
                  <el-option label="是" :value="1"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="发货时间" >
                <el-date-picker class="width220 noMargin" v-model="dialog.formData.deliverTime" type="datetime" placeholder="发货时间"></el-date-picker>
              </el-form-item>
              <h3 class="dialog-plate-title">收货信息</h3>
              <el-form-item label="是否到货" >
                <el-select v-model="dialog.formData.isArrive"  placeholder="请选择是否到货" class="width220">
                  <el-option label="否" :value="0"></el-option>
                  <el-option label="是" :value="1"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="到货时间" >
                <el-date-picker class="width220 noMargin" v-model="dialog.formData.arriveAddTime" type="datetime" placeholder="到货时间"></el-date-picker>
              </el-form-item>
              <el-form-item label="库房人员"><el-input v-model="dialog.formData.kfPersonName" class="width220"></el-input></el-form-item>

              <h3 class="dialog-plate-title">财务信息</h3>
              <el-form-item label="货款是否已结" >
                <el-select v-model="dialog.formData.isPay"  placeholder="请选择货款是否已结" class="width220">
                  <el-option label="否" :value="0"></el-option>
                  <el-option label="是" :value="1"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="付款金额"><el-input v-model="dialog.formData.paySum" class="width220" placeholder="付款金额"></el-input></el-form-item>
              <el-form-item label="付款时间" >
                <el-date-picker class="width220 noMargin" v-model="dialog.formData.payTime" type="datetime" placeholder="付款时间"></el-date-picker>
              </el-form-item>
              <el-form-item label="付款创建时间" >
                <el-date-picker class="width220 noMargin" v-model="dialog.formData.payAddTime" type="datetime" placeholder="付款创建时间" disabled></el-date-picker>
              </el-form-item>
              <el-form-item label="是否收到发票" >
                <el-select v-model="dialog.formData.isReceiveInvoice"  placeholder="请选择是否收到发票" class="width220">
                  <el-option label="否" :value="0"></el-option>
                  <el-option label="是" :value="1"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="发票号"><el-input v-model="dialog.formData.invoiceCode" class="width220" placeholder="发票号"></el-input></el-form-item>
              <el-form-item label="开票日期" >
                <el-date-picker class="width220 noMargin" v-model="dialog.formData.receiveInvoiceTime" type="datetime" placeholder="开票日期"></el-date-picker>
              </el-form-item>
              <el-form-item label="发票创建日期" >
                <el-date-picker class="width220 noMargin" v-model="dialog.formData.receiveInvoiceAddTime" type="datetime" placeholder="发票创建日期" disabled></el-date-picker>
              </el-form-item>
              <el-form-item label="财务人员"><el-input v-model="dialog.formData.cwPersonName" class="width220"></el-input></el-form-item>
              <el-form-item label="任务完成时间" >
                <el-date-picker class="width220 noMargin" v-model="dialog.formData.taskFinishTime" type="datetime" placeholder="任务完成时间" disabled></el-date-picker>
              </el-form-item>
              <el-form-item label="总金额"  v-if="dialog.type!=='insert'"><el-input v-model="dialog.formData.totals" class="width220" disabled></el-input></el-form-item>
              <h3 class="dialog-plate-title">凭证上传</h3>
              <el-row>
                <el-col :span="12" >
                  <el-col :span="6" class="text-right">支付凭证：</el-col>
                  <el-col :span="18" class="uploadPhoto">
                  <el-upload class="avata-uploader" :action="actionUrl" :show-file-list="false" :on-success="handleAvatarSuccess1" :before-upload="beforeAvatarUpload">
                      <img v-if="dialog.formData.payEvidence" :src="dialog.formData.payEvidence" class="avatar">
                      <i v-else class="el-icon-plus avata-uploader-icon">支付凭证</i>
                  </el-upload>
                  </el-col>
                </el-col>
                <el-col :span="12">
                    <el-col :span="6" class="text-right">收货凭证：</el-col>
                    <el-col :span="18" class="uploadPhoto">
                      <el-upload class="avata-uploader" :action="actionUrl" :show-file-list="false" :on-success="handleAvatarSuccess2" :before-upload="beforeAvatarUpload">
                        <img v-if="dialog.formData.receiveEvidence" :src="dialog.formData.receiveEvidence" class="avatar">
                        <i v-else class="el-icon-plus avata-uploader-icon">收货凭证</i>
                      </el-upload>
                    </el-col>
                </el-col>
              </el-row>
              </div>
              <el-form-item class="form-item-block text-center" >
                <el-button type="primary" @click="submitList">确 定</el-button>
              </el-form-item>
            </el-form>
          </el-tab-pane>
          <el-tab-pane label="采购物品列表" name="2" v-if="dialog.type!=='insert'">
            <el-button @click="showDialog1('insert')" type="primary" size="small" v-if="status==='0'&&!postData.isPay&&!postData.isArrive">新增</el-button>
            <el-table :data="cgTableList" stripe border class="user-table"   style="width: 100%;">
              <el-table-column fixed type="index" label="序号" sortable min-width="30"></el-table-column>
              <el-table-column prop="bomNameName.name" label="物料名称" sortable min-width="100"></el-table-column>
              <el-table-column prop="type" label="型号" sortable width="60" > </el-table-column>
              <el-table-column prop="nums" label="数量" sortable width="60"></el-table-column>
              <el-table-column prop="price" label="单价" sortable width="60"></el-table-column>
              <el-table-column prop="total" label="总价" sortable width="60"></el-table-column>
              <el-table-column prop="actNums" label="实际数量" sortable width="60"></el-table-column>
              <el-table-column prop="actPrice" label="实际单价" sortable width="60"></el-table-column>
              <el-table-column prop="actTotal" label="实际总价" sortable width="60"></el-table-column>
              <el-table-column prop="isBuy" label="是否到货" width="40"  align="center">
                <template slot-scope="scope">
                  <span v-if="scope.row.isBuy ===1" class='el-icon-circle-check  cl-success fn-size18 '></span>
                </template>
              </el-table-column>
              <el-table-column prop="planArriveTime" label="计划到达时间" sortable width="80" :formatter="timeFormatter"></el-table-column>
              <el-table-column prop="planPayTime" label="计划支付时间" sortable width="80" :formatter="timeFormatter"></el-table-column>
              <el-table-column prop="arriveTime" label="到货时间" sortable width="80" :formatter="timeFormatter"></el-table-column>
              <el-table-column prop="remark" label="备注" sortable min-width="100"></el-table-column>
              
              <el-table-column prop="kfPersonName" label="库房人员" sortable width="100"></el-table-column>
              <el-table-column prop="creatorName" label="创建人" sortable width="100"></el-table-column>
              <el-table-column prop="createTime" label="创建时间" sortable width="100" :formatter="timeFormatter"></el-table-column>
              <el-table-column fixed="right" label="操作" align="right" min-width="100">
                <template slot-scope="scope">
                  <el-button @click="showDialog1('update',scope.row)" type="text" size="small">编辑</el-button>
                  <el-button @click="showDialog1('arrive',scope.row)" type="text" size="small" v-if="postData.isArrive">到货</el-button>
                  <el-button @click="showDialog1('delete',scope.row)" type="text" size="small" v-if="status==='0'&&!postData.isPay&&!postData.isArrive"><span class="cl-danger">删除</span></el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
         </el-tabs>
    </el-dialog>
     <!-- 新增修改采购物品列表 -->
    <el-dialog :title="dialog1.title" width="900px" center :visible.sync="dialog1.isShow" :close-on-click-modal="false" style="padding-bottom: 15px;" v-dialogDrag>
      <el-form :inline="true" class="demo-form-inline" v-model="dialog1.fromData" label-position="right" label-width="180px">
        <el-form-item label="物料名称">
          <el-autocomplete  class="width220"  v-model="dialog1.fromData.bomNameName.name" :fetch-suggestions="asyncBom" placeholder="请输入物料名称" @select="changebom" :disabled='status==="1"||(!!postData.isPay||!!postData.isArrive)'></el-autocomplete>
        </el-form-item>
        <el-form-item label="规格型号"><el-input  class="width220" v-model="dialog1.fromData.type" :disabled='status==="1"||(!!postData.isPay||!!postData.isArrive)'></el-input></el-form-item>
        <el-form-item label="计划数量"><el-input  class="width220" v-model="dialog1.fromData.nums" :disabled='status==="1"||(!!postData.isPay||!!postData.isArrive)'></el-input></el-form-item>
        <el-form-item label="计划单价"><el-input  class="width220" v-model="dialog1.fromData.price" :disabled='status==="1"||(!!postData.isPay||!!postData.isArrive)'></el-input></el-form-item>
        <el-form-item label="计划总价"><el-input  class="width220" v-model="dialog1.fromData.total" disabled></el-input></el-form-item>
        <el-form-item label="计划到达时间"><el-date-picker v-model="dialog1.fromData.planArriveTime" type="date" placeholder="选择日期" class="width220 noMargin" :disabled='status==="1"||(!!postData.isPay||!!postData.isArrive)'></el-date-picker></el-form-item>
        <el-form-item label="计划支付时间"><el-date-picker v-model="dialog1.fromData.planPayTime" type="date" placeholder="选择日期" class="width220 noMargin" :disabled='status==="1"||(!!postData.isPay||!!postData.isArrive)'></el-date-picker></el-form-item>
        <el-form-item label="实际数量"><el-input  class="width220" v-model="dialog1.fromData.actNums"  :disabled='status==="1"||!postData.isArrive'></el-input></el-form-item>
        <el-form-item label="商品实际单价"><el-input  class="width220" v-model="dialog1.fromData.actPrice"  :disabled='status==="1"||!postData.isPay'></el-input></el-form-item>
        <el-form-item label="商品实际总价"><el-input  class="width220" v-model="dialog1.fromData.actTotal" disabled></el-input></el-form-item>
        <el-form-item label="备注"><el-input  class="width220" v-model="dialog1.fromData.remark"></el-input></el-form-item>
        <el-form-item label="创建人" v-if="dialog1.type!='insert'"><el-input  class="width220" v-model="dialog1.fromData.creatorName" disabled></el-input></el-form-item>
        <el-form-item label="创建时间" v-if="dialog1.type!='insert'"><el-input  class="width220" v-model="dialog1.fromData.createTime" disabled></el-input></el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center;">
        <el-button @click="submitProcessStateList" type="primary">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import purchaseApi from 'plugins/axios/purchaseApi.js';
import baseApi from 'plugins/axios/baseApi.js';
import purchaseTaskList from 'views/components/purchaseTaskList.vue' /**任务列表 */

export default {
  components: {
    purchaseTaskList
  },
  data(){
    return {
      status:'0',
      postData:{
        isPay:null,
        isArrive:null
      },
      allCgPersonList:[],
      actionUrl:baseApi.imageUpload(),
      machineAllList:[],/**所有机器列表 */
      search:{
        orderNums:"",
        supplier:"",
        supplierName:"",
        taskCode:""
      },
      dialog:{/**弹框配置 */
        title:'',
        isShow:false,
        type:'',
        formData:{
          supplierName:{}
        },
        activeName:'1'
      },
      dialog1:{
        title:'',
        type:'',
        isShow:false,
        fromData:{
          bomNameName:{}
        }
      },
      cgTableList:[]/**采购物品列表 */
    }
  },
  created(){},
  mounted(){
    this.status = this.$route.query.status;
    this.postData.isPay = this.$route.query.isPay?this.$route.query.isPay:null,
    this.postData.isArrive = this.$route.query.isArrive?this.$route.query.isArrive:null;
    this.getTablList();
  },
  watch: {
    $route(){
      this.status = this.$route.query.status;
      this.postData.isPay = this.$route.query.isPay?this.$route.query.isPay:null,
      this.postData.isArrive = this.$route.query.isArrive?this.$route.query.isArrive:null;
      this.search.orderNums="";
      this.search.supplier="";
      this.search.supplierName="";
      this.search.taskCode="";
      this.getTablList();
    }
  },
  methods:{
    /**时间格式化 */
    timeFormatter(row, column, cellValue, index){
      return cellValue?this.timestampToTime(cellValue,'mm-dd'):'';
    },
    /**29所计划列表 */
    getTablList(){
      let self = this;
      self.postData.state=self.status;
      self.postData.orderNums = self.search.orderNums;
      self.postData.supplier = self.search.supplierName===''?null:self.search.supplier;
      self.postData.taskCode = self.search.taskCode===''?null:self.search.taskCode;
      self.$refs.tableList29.get29TableList()
    },
    /**获取采购人员列表 */
    getAllCgPersons(){
      let self = this;
      baseApi.getAllCgPersons().then(res=>{
        self.allCgPersonList = res.content;
      })
    },
    searchBtn(){
      this.getTablList();
    },
    showDialog(type,row){
      this.dialog.type =type;
      this.dialog.isShow=true;
      this.dialog.activeName="1";

      switch(type){
        case 'insert':
          this.getAllCgPersons();
          this.dialog.formData={
            supplierName:{}
          };
          this.dialog.title = '新增采购计划任务';
          break;
        case 'update':
          this.getAllCgPersons();
          this.dialog.formData = JSON.parse(JSON.stringify(row));
          this.dialog.title = '修改采购计划任务';
          break;
      } 
    },
    submitList(formName){
      let self = this;
      let postData =JSON.parse(JSON.stringify(self.dialog.formData));
      postData.stockUpTime =postData.stockUpTime?self.timestampToTime(postData.stockUpTime):null
      postData.checkUpTime =postData.checkUpTime?self.timestampToTime(postData.checkUpTime):null
      postData.deliverTime =postData.deliverTime?self.timestampToTime(postData.deliverTime):null
      postData.arriveAddTime = postData.arriveAddTime?self.timestampToTime(postData.arriveAddTime):null
      postData.payTime = postData.payTime?self.timestampToTime(postData.payTime):null
      postData.receiveInvoiceTime = postData.receiveInvoiceTime?self.timestampToTime(postData.receiveInvoiceTime):null
      postData.taskFinishTime = postData.taskFinishTime?self.timestampToTime(postData.taskFinishTime):null
      delete postData.supplierName;
      purchaseApi.insertUpdateCgTask(self.dialog.type,postData).then(res=>{
        self.$message.success(`${self.dialog.title}成功`);
        self.dialog.isShow=false;
        self.getTablList()
      })
    },
    querySearchAsync(queryString, callback){
      purchaseApi.searchSupplierList({keyWord:queryString?queryString:''}).then(res=>{
        res.content.forEach(item=>{
          item.value = item.name;
        })
         callback(res.content);
      })
     ;
    },
    handleSelect(item){
      this.search.supplier = item.id;
    },
    handleSelect1(item){
      this.dialog.formData.supplier = item.id;
    },
    beforeAvatarUpload(file){/**图片上传前图片大小验证*/
      const isJPG = file.type.substr(0,5) === 'image';
      const isLt10M = file.size / 1024 / 1024 < 10;
      if (!isJPG) {
        this.$message.error('只能上传图片!');
      }
      if (!isLt10M) {
        this.$message.error('上传头像图片大小不能超过 10MB!');
      }
      return isJPG && isLt10M
    },
    handleAvatarSuccess1(response, file, fileList){
      this.dialog.formData.payEvidence = response.content;
    },
    handleAvatarSuccess2(response, file, fileList){
      this.dialog.formData.receiveEvidence = response.content;
    },
    handleClick(){
      let self = this;
      switch(self.dialog.activeName){
        case '2':
         self.getCgTableList();
        break;
      }
    },
    getCgTableList(){
      let self = this;
      purchaseApi.cgMaterialDetailList(self.dialog.formData.id).then(res=>{
        self.cgTableList= res.content;
      })
    },
    showDialog1(type,row){
      let self =this;
      self.dialog1.type = type;
      switch(type){
        case 'insert':
          self.dialog1.isShow =true;
          self.dialog1.title = '新增采购物品';
          self.dialog1.formData={}
          break;
        case 'update':
          self.dialog1.isShow =true;
          self.dialog1.title = '修改采购物品';
          self.dialog1.fromData = JSON.parse(JSON.stringify(row));
          break;
        case 'delete':
          self.$confirm('是否删除此采购物品?', '提示', {
            confirmButtonText: '删除',
            cancelButtonText: '取消',
            confirmButtonClass:'bg-warning noBorder',
            type: 'warning'
          }).then(() => {
          purchaseApi.deleteCgMaterialDetail(row.id).then(res=>{
            self.$message.success('删除成功!');
            self.getCgTableList();
          })
        }).catch(() => {});
          break;
        case 'arrive':
          self.$confirm('是否确认到货?', '提示', {
            confirmButtonText: '到货',
            cancelButtonText: '取消',
            type: 'success'
          }).then(() => {
            self.dialog1.fromData = JSON.parse(JSON.stringify(row));
            self.dialog1.fromData.actNums =self.dialog1.fromData.nums
            self.submitProcessStateList('update',()=>{
              self.$message.success('到货成功!');
               self.getCgTableList();
            })
        }).catch(() => {});
          break;
      }
    },
    submitProcessStateList(e,cb){
      let self = this;
      let postData =JSON.parse(JSON.stringify(self.dialog1.fromData));
      postData.planArriveTime=postData.planArriveTime?self.timestampToTime(postData.planArriveTime):null;
      postData.planPayTime=postData.planPayTime?self.timestampToTime(postData.planPayTime):null;
      delete postData.bomNameName;
      if(self.dialog1.type==='insert'){
        postData.tid = self.dialog.formData.id;
      }
      purchaseApi.insertUpdateCgMaterialDetail((self.dialog1.type==='arrive'?'update':self.dialog1.type),postData).then(res=>{
        if(cb){
          cb();
        }else{
          self.dialog1.isShow = false;
          self.getCgTableList();
          self.$message.success(`${self.dialog1.title}成功`);
        }
      })
    },
    asyncBom(queryString, callback){
      let result=[];
      purchaseApi.materialListBySupplierId(this.dialog.formData.supplier).then(res=>{
        if(res.content&&res.content.length>0){
          res.content.forEach(element => {
          element.value = element.name;
          });
        }
        result = res.content;
        callback(result);
      })
    },
    changebom(item){
      this.dialog1.fromData.bomName=item.id;
      this.dialog1.fromData.type=item.type;
    },
  }
}
</script>
<style lang="stylus" scoped>
  .addRole
    padding-bottom 10px
  .content-rowspan div
    padding-left: 13px;
    line-height: 46px;
    border-bottom: 1px solid #ECEDEE;
    &:last-child
       border-bottom:none
</style>
